package com.daguchuangyi.erp_android.productlist;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.daguchuangyi.erp_android.R;
import com.daguchuangyi.erp_android.base.CompatStatusBarActivity;
import com.daguchuangyi.erp_android.login.LoginActivity;
import com.daguchuangyi.erp_android.manager.UserInfoManager;
import com.daguchuangyi.erp_android.model.LocalMediaWrapper;
import com.daguchuangyi.erp_android.productlist.classifiaction.ClassificationManager;
import com.daguchuangyi.erp_android.productlist.classifiaction.ClassificationMenuDialog;
import com.daguchuangyi.erp_android.productlist.imagetell.ImageCropActivity;
import com.daguchuangyi.erp_android.productlist.parametersetting.ParamsSettingDialog;
import com.daguchuangyi.erp_android.productlist.paramsfilter.ParamsFilterFragment;
import com.daguchuangyi.erp_android.productlist.productsummary.ProductSummaryFragment;
import com.daguchuangyi.erp_android.productlist.widget.AccountQuitDialog;
import com.daguchuangyi.erp_android.productlist.widget.CameralActionDialog;
import com.daguchuangyi.erp_android.productlist.widget.NoClassifiactionWarnningDialog;
import com.daguchuangyi.erp_android.util.ImageUtil;
import com.daguchuangyi.erp_android.util.PermissionUtils;
import com.jude.utils.JUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;

import rx.subscriptions.CompositeSubscription;

public class ProductionSummaryActivity extends CompatStatusBarActivity
        implements ParamsFilterFragment.OnFilterSelectListener, ClassificationManager.OnClassificationChangeListener {
    private static final String TAG = "ProductionSummaryActivity";
    private static final int CUT_PICTURE_CODE = 0x77;

    private ImageView mAvatarIv;

    private ViewGroup mStyleCheckView;
    private ImageView mStyleIconIv;
    private TextView mStyleContentTv;

    private ViewGroup mParamsCheckView;
    private ImageView mParamsIconIv;
    private TextView mParamsContentTv;

    private ViewGroup mParamSettingWrapper;

    private ProductSummaryFragment mProductSummaryFragment;
    private ParamsFilterFragment mParamsFilterFragment;

    private TextView mClassificationTv;

    private CompositeSubscription mCompositeSubscription = new CompositeSubscription();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_production_summary);
        setImmersiveStatusBar(false, getResources().getColor(R.color.colorPrimaryDark));

        mAvatarIv = (ImageView) findViewById(R.id.avatar_iv);
        mAvatarIv.setOnClickListener(view -> {
            AccountQuitDialog quitDialog = new AccountQuitDialog();
            quitDialog.setOnDeleteChooseListener(new AccountQuitDialog.OnDeleteChooseListener() {
                @Override
                public void onDeleteConfirm() {
                    ProductionSummaryActivity.this.finish();
                    Intent intent = new Intent(ProductionSummaryActivity.this, LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }

                @Override
                public void onDeleteCancel() {
                    //leave empty
                }
            });
            quitDialog.show(getSupportFragmentManager(), "quitDialog");
        });

        findViewById(R.id.cameral_iv).setOnClickListener(v -> {

//            if (TextUtils.equals(ClassificationManager.getInstance().getExtralMode(), ClassificationManager.MODE_EXTRA_KEY_LIKE)) {
//                JUtils.ToastLong("当前分类无效,请重新选择");
//                return;
//            }

            if (!ClassificationManager.getInstance().hasClassificationCheck()) {
                NoClassifiactionWarnningDialog dialog = new NoClassifiactionWarnningDialog();
                dialog.show(getSupportFragmentManager(), "NoClassificationWarn");
                return;
            }

            if (TextUtils.equals(ClassificationManager.getInstance().getClassificationId(), ClassificationManager.ID_NO_IMAGE_TAG)) {
                JUtils.ToastLong("当前分类不支持图片识别功能");
                return;
            }

            CameralActionDialog cameralActionDialog = new CameralActionDialog();
            cameralActionDialog.setOnCameralActionListener(new CameralActionDialog.OnCameralActionListener() {
                @Override
                public void onCancelClick() {
                    //leave empty
                }

                @Override
                public void onGalleryClick() {
                    PictureSelector.create(ProductionSummaryActivity.this)
                            .openGallery(PictureMimeType.ofImage())
                            .theme(R.style.picture_white_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                            .maxSelectNum(1)// 最大图片选择数量 int
                            .minSelectNum(1)// 最小选择数量 int
                            .imageSpanCount(4)// 每行显示个数 int
                            .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                            .previewImage(true)// 是否可预览图片 true or false
                            .isCamera(false)// 是否显示拍照按钮 true or false
                            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                            .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                            .enableCrop(false)// 是否裁剪 true or false
                            .isGif(false)// 是否显示gif图片 true or false
                            .openClickSound(false)// 是否开启点击声音 true or false
                            .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                            .synOrAsy(true)//同步true或异步false 压缩 默认同步
                            .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                }

                @Override
                public void onTakePictureClick() {

                    if (PermissionUtils.isCameraCanUse()) {
                        PictureSelector.create(ProductionSummaryActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .theme(R.style.picture_white_style)
                                .selectionMode(PictureConfig.SINGLE)
                                .isCamera(true)
                                .enableCrop(false)
                                .glideOverride(160, 160)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    } else {
                        JUtils.Toast("无法拍照,请检查权限设置");
                    }
                }
            });
            cameralActionDialog.show(getSupportFragmentManager());
        });

        mStyleCheckView = (ViewGroup) findViewById(R.id.product_style_wrapper);
        mStyleIconIv = (ImageView) findViewById(R.id.product_style_icon);
        mStyleContentTv = (TextView) findViewById(R.id.product_style_tv);

        mParamsCheckView = (ViewGroup) findViewById(R.id.params_wrapper);
        mParamsIconIv = (ImageView) findViewById(R.id.params_icon);
        mParamsContentTv = (TextView) findViewById(R.id.params_tv);

        mParamSettingWrapper = (ViewGroup) findViewById(R.id.product_menu_wrapper);
        mParamSettingWrapper.setOnClickListener(v -> {
            ClassificationMenuDialog menuDialog = new ClassificationMenuDialog();
            menuDialog.show(getSupportFragmentManager());
        });

        mProductSummaryFragment = new ProductSummaryFragment();
        mParamsFilterFragment = new ParamsFilterFragment();

        mClassificationTv = (TextView) findViewById(R.id.classification_tv);
        mClassificationTv.setText(ClassificationManager.getInstance().getCurrentClassification());

        ClassificationManager.getInstance().setClassificationChangeListener(this);

        initView();
        loadData();
    }

    private void loadData() {
        if (UserInfoManager.getUserInfoManager().getUserInfoModel() == null) {
            JUtils.ToastLong("登录状态已过期，请重新登录");
            ProductionSummaryActivity.this.finish();
            startActivity(new Intent(ProductionSummaryActivity.this, LoginActivity.class));
        } else {
            String avatarUrl = UserInfoManager.getUserInfoManager().getUserInfoModel().getUser().getAvatar();
            Glide.with(this)
                    .applyDefaultRequestOptions(ImageUtil.getAvatarRequestOptions())
                    .load(avatarUrl)
                    .into(mAvatarIv);
        }
    }

    private void initView() {
        ProductSummaryManager.getInstance().setCurrentState(ProductSummaryManager.STYLE_LIST);

        getSupportFragmentManager().beginTransaction()
                .add(R.id.content_layout, mProductSummaryFragment)
                .commit();

        findViewById(R.id.setting_wrapper).setOnClickListener(v -> {
            boolean isInLikelyMode = TextUtils.equals(ClassificationManager.getInstance().getExtralMode(), ClassificationManager.MODE_EXTRA_KEY_LIKE);
            if (ClassificationManager.getInstance().hasClassificationCheck() || isInLikelyMode) {
                ParamsSettingDialog paramsSettingDialog = new ParamsSettingDialog();
                paramsSettingDialog.show(getSupportFragmentManager());
            } else {
                NoClassifiactionWarnningDialog dialog = new NoClassifiactionWarnningDialog();
                dialog.show(getSupportFragmentManager(), "NoClassificationWarn");
            }

        });

        initStyleState();

        mStyleCheckView.setOnClickListener(v -> {
            int style = ProductSummaryManager.getInstance().getCurrentState();
            if (style == ProductSummaryManager.STYLE_LIST) {
                ProductSummaryManager.getInstance().setCurrentState(ProductSummaryManager.STYLE_GRID);
            } else {
                ProductSummaryManager.getInstance().setCurrentState(ProductSummaryManager.STYLE_LIST);
            }
            refreshStyleState();
        });

        mParamsCheckView.setOnClickListener(v -> {
//            if (TextUtils.equals(ClassificationManager.getInstance().getExtralMode(), ClassificationManager.MODE_EXTRA_KEY_LIKE)) {
//                JUtils.ToastLong("当前分类无效,请重新选择");
//                return;
//            }

            if (ClassificationManager.getInstance().hasClassificationCheck()) {
                if (!mParamsFilterFragment.isAdded()) {
                    showParamsFragment();
                } else {
                    hideParamsFragment();
                }
            } else {
                NoClassifiactionWarnningDialog dialog = new NoClassifiactionWarnningDialog();
                dialog.show(getSupportFragmentManager(), "NoClassificationWarn");
            }

        });

    }

    private void hideParamsFragment() {
        getSupportFragmentManager().beginTransaction()
                .setCustomAnimations(R.anim.slide_in_from_top, R.anim.slide_out_to_top)
                .remove(mParamsFilterFragment)
                .commitAllowingStateLoss();

        @ColorInt int highlightColor = ContextCompat.getColor(this, R.color.normalGrey);
        DrawableCompat.setTint(mParamsIconIv.getDrawable(), highlightColor);
        mParamsContentTv.setTextColor(highlightColor);

        mStyleCheckView.setClickable(true);
        mParamSettingWrapper.setClickable(true);
    }

    private void showParamsFragment() {
        getSupportFragmentManager().beginTransaction()
                .setCustomAnimations(R.anim.slide_in_from_top, R.anim.slide_out_to_top)
                .add(R.id.content_layout, mParamsFilterFragment)
                .commitAllowingStateLoss();

        @ColorInt int highlightColor = ContextCompat.getColor(this, R.color.hightLightBlue);
        DrawableCompat.setTint(mParamsIconIv.getDrawable(), highlightColor);
        mParamsContentTv.setTextColor(highlightColor);

        mStyleCheckView.setClickable(false);
        mParamSettingWrapper.setClickable(false);
    }

    private void refreshStyleState() {
        initStyleState();
        mProductSummaryFragment.refreshStyleState();
    }

    private void initStyleState() {
        int currentStyle = ProductSummaryManager.getInstance().getCurrentState();
        if (currentStyle == ProductSummaryManager.STYLE_GRID) {
            @ColorInt int highlightColor = ContextCompat.getColor(this, R.color.hightLightBlue);
            DrawableCompat.setTint(mStyleIconIv.getDrawable(), highlightColor);
            mStyleContentTv.setTextColor(highlightColor);
        } else if (currentStyle == ProductSummaryManager.STYLE_LIST) {
            @ColorInt int highlightColor = ContextCompat.getColor(this, R.color.normalGrey);
            DrawableCompat.setTint(mStyleIconIv.getDrawable(), highlightColor);
            mStyleContentTv.setTextColor(highlightColor);
        }

    }

    @Override
    public void onCancelClicked() {
        hideParamsFragment();
    }

    @Override
    public void onConfirmClicked() {
        hideParamsFragment();
//        mProductSummaryFragment.refreshData(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    ArrayList<LocalMedia> selectList = new ArrayList<>(PictureSelector.obtainMultipleResult(data));
                    Intent intent = new Intent(ProductionSummaryActivity.this, ImageCropActivity.class);
                    intent.putExtra(ImageCropActivity.KEY_URLS, selectList);
                    startActivityForResult(intent, CUT_PICTURE_CODE);
                    break;
                case CUT_PICTURE_CODE:
                    LocalMediaWrapper localMediaWrapper = data.getParcelableExtra(ImageCropActivity.TAG_CROP_RESULTS);
                    boolean isTotalRecognize = data.getBooleanExtra(ImageCropActivity.TAG_CROP_TYPE, true);
                    mProductSummaryFragment.addHeader(localMediaWrapper, isTotalRecognize);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ClassificationManager.getInstance().setClassificationChangeListener(null);
    }

    @Override
    public void onClassificationChanged(String classification) {
        JUtils.Log(TAG, "onClassificationChanged");
        hideParamsFragment();
        mClassificationTv.setText(classification);
        if (!ClassificationManager.getInstance().hasImageRecognizeChecke()) {
            mProductSummaryFragment.removeHeader();
        }
        if (!TextUtils.equals(ClassificationManager.getInstance().getExtralMode(),
                ClassificationManager.MODE_EXTRA_KEY_RECOGNITION)) {
            mProductSummaryFragment.refreshData(true);
        } else {
            mProductSummaryFragment.refreshData(false);
        }
    }
}
